<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生信息管理</title>
    <style>
        table {
            margin-top: 40px;
            width: 100%;
            border-collapse: collapse;
            border: 2px solid #333;
        }

        th,
        td {
            padding: 10px;
            text-align: center;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f2f2f2;
            color: #333;
        }

        tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        tr:nth-child(odd) {
            background-color: #a2cb89;
        }

        tbody tr:nth-child(odd) {
            background-color: #d9d9d9;
        }

        table thead tr td {
            font: 1.5em sans-serif;
        }

        table caption {
            font: 2em sans-serif;
        }
    </style>
</head>

<body>
    <label>姓名：</label><input type="text" placeholder="请输入学生姓名" id="name">
    <label>性别：</label>
    <select id="gender">
        <option value="男">男</option>
        <option value="女">女</option>
    </select>
    <label>年龄：</label><input type="text" placeholder="请输入学生年龄" id="age">
    <input type="submit" value="提交" onclick="setInfo();">

    <table>
        <caption>22级软件1班学生信息表</caption>
        <thead>
            <tr>
                <td>姓名</td>
                <td>性别</td>
                <td>年龄</td>
            </tr>
        </thead>
        <tbody id="students">
        </tbody>
    </table>

    <script>
        let tbody = document.getElementById('students');
        let students = new Array();
        initStudents();
        showStudents();

        function initStudents(){
            let json_stu = sessionStorage.getItem('students');//取出存储
            if(json_stu){
                students = JSON.parse(json_stu);
            }else{
                console.log('本地存储里面没有学生信息');
            } 
        }

        function showStudents(){
            tbody.innerHTML ='';
            for(let i=0;i<students.length;i++){
                let stu = students[i];
                tbody.innerHTML = tbody.innerHTML+'<tr><td>' + stu.name + '</td><td>' + stu.gender + '</td><td>' + stu.age + '</td></tr>';
            }
        }

        function setInfo() {
            let name = document.getElementById('name').value;
            let gender = document.getElementById('gender').value;
            let age = document.getElementById('age').value;
            students.push({ name:name,gender:gender,age:age});    
            sessionStorage.setItem('students',JSON.stringify(students)); //存入存储   
            showStudents();
        }
    </script>
</body>

</html>